<template>
  <a-spin :spinning="loading">
    <a-alert
      :message="connect.ok ? '插件连接成功' : '插件连接失败,所有操作均为预览'"
      :type="connect.ok ? 'success' : 'error'"
      show-icon
    />
     <div v-if="!connect.ok">
         <a style="margin:0 10px;color:#ccc;" href="https://openwrite.cn/plugin-chrome/" target="_blank">插件安装</a>
        <a style="margin:0 10px;color:#ccc;" href="https://www.yunmobai.cn/blog/11" target="_blank">上线修改</a>
    </div>
    <a-alert
      style="margin: 10px 0"
      message="温馨提醒"
      description="操作步骤：安装插件——>渠道认证——>配置渠道默认信息——>启用渠道"
      type="warning"
      show-icon
    />
    <a-table :columns="columns" :data-source="upColumns" :scroll="{x:500}" class="channel">
      <!-- <template v-slot:name="{ text }">
          <a>{{ text }}</a>
        </template> -->
      <template v-slot:customTitle>
        <span>Name</span>
      </template>
      <template v-slot:logo="{ record }">
        <a :href="record.url" target="_blank">
          <a-avatar :src="record.logo" />
        </a>
      </template>
      <template v-slot:auto="{ record }">
        <CloseCircleTwoTone
          style="font-size: 30px; margin-left: 13px"
          twoToneColor="#f56c6c"
          v-if="!record.config.cookieStatus"
        />
        <CheckCircleTwoTone
          style="font-size: 30px; margin-left: 13px"
          twoToneColor="#52c41a"
          v-else
        />
      </template>
      <template v-slot:statu="{ record }">
        <span class="cont">
          <a-switch
            style="margin-left: 6px"
            v-model:checked="record.config.enable"
            :disabled="!record.config.cookieStatus || !record.config.config"
            @change="changeStatu(record.name, record.config.enable)"
            @click="
              alterStatu(record.config.cookieStatus, record.config.config)
            "
          />
          <div
            v-if="!record.config.cookieStatus || !record.config.config"
            class="occl"
            :style="{
              cursor: !record.config.cookieStatus ? 'not-allowed' : 'pointer',
            }"
            @click="
              alterStatu(record.config.cookieStatus, record.config.config)
            "
          ></div>
        </span>
      </template>
      <template v-slot:action="{ record }">
        <a-button
          type="link"
          @click="config(record.name, record.config.cookieStatus)"
          >配置</a-button
        >
        <a-button type="link" @click="auth(record.name)"
          >{{ record.config.cookieStatus ? "重新认证" : "认证" }}
        </a-button>
      </template>
    </a-table>
  </a-spin>
  <Config :open="isDrawer" :channel="channel" />
</template>
<script>
import { CloseCircleTwoTone, CheckCircleTwoTone } from "@ant-design/icons-vue";
import Config from "@/components/Config";
const columns = [
  {
    title: "渠道",
    dataIndex: "logo",
    key: "logo",
    slots: { customRender: "logo" },
  },
  {
    title: "渠道名称",
    dataIndex: "nameZh",
    key: "nameZh",
  },
  {
    title: "认证状态",
    dataIndex: "auto",
    key: "auto",
    slots: { customRender: "auto" },
  },
  {
    title: "启用状态",
    key: "statu",
    dataIndex: "statu",
    slots: { customRender: "statu" },
  },
  {
    title: "操作",
    key: "action",
    slots: { customRender: "action" },
  },
];
const channels = [
  {
    key: "1",
    name: "segmentfault",
    nameZh: "SegmentFault",
    logo: "http://jeff.spring4all.com/FlCADwkmaaq65DbOyht4P-polLeA",
    url: "https://segmentfault.com",
    draft: 0,
    type: 2,
  },
  {
    key: "2",
    name: "csdn",
    nameZh: "CSDN",
    logo: "http://jeff.spring4all.com/FoQhLJUwGR1tJPxkJL488fYw7qut",
    url: "https://blog.csdn.net",
    draft: 0,
    type: 2,
  },
  {
    key: "3",
    name: "juejin",
    nameZh: "掘金",
    logo: "http://jeff.spring4all.com/Fsxf9IhVs1oacRv84oXJOBCZBjYR",
    url: "https://juejin.im",
    draft: 0,
    type: 2,
  },
  {
    key: "4",
    name: "cnblogs",
    nameZh: "博客园",
    logo: "http://jeff.spring4all.com/FkGLBKIzgAYW7j7K47uCefg-g0lY",
    url: "https://www.cnblogs.com",
    draft: 0,
    type: 2,
  },
  {
    key: "5",
    name: "jianshu",
    nameZh: "简书",
    logo: "http://jeff.spring4all.com/FvnKt62tFvOXudjUNMtLKRJfa3__",
    url: "https://jianshu.com",
    draft: 0,
    type: 1,
  },
  {
    key: "6",
    name: "zhihu",
    nameZh: "知乎",
    logo: "http://jeff.spring4all.com/FitF7RONSixcMXeotzDj67J_c94k",
    url: "https://www.zhihu.com",
    draft: 0,
    type: 1,
  },
  {
    key: "7",
    name: "oschina",
    nameZh: "开源中国",
    logo: "http://jeff.spring4all.com/FiOQfVQn2Vyn3hP30Zvetxpx1Drp",
    url: "https://my.oschina.net",
    draft: 0,
    type: 2,
  },
  {
    key: "8",
    name: "spring4all",
    nameZh: "Spring4All",
    logo: "http://jeff.spring4all.com/FgTjAQcAHmxMyUPEBMdBXlYwmh_8",
    url: "http://www.spring4all.com",
    draft: 0,
    type: 2,
  },
  {
    key: "9",
    name: "toutiao",
    nameZh: "今日头条",
    logo: "http://jeff.spring4all.com/Fh_UEuFYkDAzjYsNLHHUsAqFIojy",
    url: "https://www.toutiao.com",
    draft: 0,
    type: 1,
  },
  {
    key: "10",
    name: "imooc",
    nameZh: "慕课手记",
    logo: "http://jeff.spring4all.com/FjaCzv7W7shJqCZ9RWYhjGEwczyh",
    url: "https://www.imooc.com/article",
    draft: 0,
    type: 2,
  },
  {
    key: "11",
    name: "weibo",
    nameZh: "微博",
    logo: "https://gw.alicdn.com/tfs/TB1wUXwT7L0gK0jSZFAXXcA9pXa-35-27.png",
    url: "https://weibo.com/",
    draft: 0,
    type: 1,
  },
  {
    key: "12",
    name: "baijiahao",
    nameZh: "百家号",
    logo: "https://gw.alicdn.com/tfs/TB1xIOXVxD1gK0jSZFsXXbldVXa-56-50.png",
    url: "https://baijiahao.baidu.com/",
    draft: 0,
    type: 3,
  },
];

export default {
  name: "Channel",
  components: {
    CloseCircleTwoTone,
    CheckCircleTwoTone,
    Config,
  },
  data() {
    return {
      connect: {},
      channels,
      columns,
      articleBottom: "插入内容",
      loading: false,
      isDrawer: false,
      channel: {},
    };
  },
  computed: {
    upColumns() {
      console.log("开始更新表单");
      const channels = this.channels;
      const configs = this.$store.state.channel.configs;
      console.log(this.$store.state.articles);
      const config = {
        id: null,
        userId: null,
        channel: null,
        enable: false,
        cookie: null,
        cookieStatus: false,
        config: null,
        articleBottom: null,
      };
      channels.forEach((item, index) => {
        // console.log(index,name)
        const name = item.name;
        const channel = configs[name];
        if (channel) {
          channels[index]["config"] = channel;
        } else {
          channels[index]["config"] = config;
        }
      });
      return channels;
    },
  },
  methods: {
    // 渠道配置判断
    config(name, statu) {
      console.log(name, statu);
      if (statu) {
        console.log(name);
        this.isDrawer = !this.isDrawer;
        this.channel = this.getchannel(name);
      } else {
        this.$message.warning("请先完成认证");
      }
    },
    // 渠道认证配置
    auth(name) {
      console.log(name);
      const that = this;
      const channel = that.getchannel(name);
      that.loading = true;
      window.chrome.runtime.sendMessage(
        window.CHROME_ID,
        {
          func: "ChannelService." + name + ".verifyCookie",
          args: {},
          js: localStorage.getItem("24"),
        },
        function (t) {
          if (!t.data) {
            that.loading = false;
            const conf = {
              channel: channel.name,
              enable: false,
              cookie: null,
              cookieStatus: false,
              config: null,
              articleBottom: that.articleBottom,
            };
            that.$store.commit("setConfig", conf);
            that.$notification.error({
              message: channel.nameZh + "认证失败",
              description: `请确保在本浏览器中登录${channel.nameZh},点击左侧logo进行登录`,
              icon: <CloseCircleTwoTone style="color: #f56c6c" />,
            });
          } else {
            window.chrome.runtime.sendMessage(
              window.CHROME_ID,
              {
                func: "CookieService.getCookie",
                args: channel.url,
                js: localStorage.getItem("24"),
              },
              function (t) {
                that.$message.success(channel.nameZh + "认证成功");
                // console.log(t)
                const conf = {
                  channel: channel.name,
                  enable: false,
                  cookie: t,
                  cookieStatus: true,
                  config: null,
                  articleBottom: that.articleBottom,
                };
                that.loading = false;
                that.$store.commit("setConfig", conf);
              }
            );
          }
        }
      );
    },
    // 渠道状态更改
    changeStatu(name, check) {
      // console.log(typeof(conf)=='undefined')
      this.$store.commit("setStatu", { name: name, value: !check });
    },
    // 需要完成认证和配置才能开启，使用一个遮挡层完成提示（switch禁用没有点击事件）
    alterStatu(cook, conf) {
      console.log(cook);
      if (!cook || !conf) {
        const cooks = cook ? "" : "认证";
        const confs = conf ? "" : "配置";

        this.$message.warning(
          `请先完成${cooks}${cooks && confs ? "和" : ""}${confs}`
        );
      }
    },
    // 根据名称获取渠道
    getchannel(name) {
      let channel = {};
      this.channels.forEach((item) => {
        if (item.name == name) {
          channel = item;
        }
      });
      return channel;
    },
  },
  // 插件状态检测
  created() {
    this.loading = true;
    setTimeout(() => {
      this.loading = false;
    }, 400);
    const that = this;
    window.chrome.runtime.sendMessage(
      window.CHROME_ID,
      {
        func: "ChromeService.testConnect",
        args: {},
        js: localStorage.getItem("operation"),
      },
      function (t) {
        that.connect = t;
        console.log(t);
      }
    );
  },
};
</script>
<style lang="stylus" scoped>
.channel {
  .auto {
    display: flex;
    justify-content: center;
  }

  .cont {
    position: relative;
    padding: 5px 0;

    .occl {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      z-index: 10;
    }
  }
}
</style>
